import QtQuick 2.15
import QtQuick.Controls 2.15
import QtQuick.Layouts 1.15

/**
 * 添加设备对话框
 * 用于添加新的 Modbus TCP 设备
 */
Dialog {
    id: root
    
    // ========================================
    // 对话框属性
    // ========================================
    title: "➕ 添加新设备"
    modal: true
    anchors.centerIn: parent
    width: Math.min(500, parent.width * 0.9)
    
    // 信号：提交添加
    signal deviceAdded(string deviceId, string deviceName, string ipAddress, int port, int slaveId, string description)
    
    // ========================================
    // 内容区
    // ========================================
    contentItem: Rectangle {
        color: "white"
        implicitHeight: contentLayout.implicitHeight + 40
        
        ColumnLayout {
            id: contentLayout
            anchors.fill: parent
            anchors.margins: 20
            spacing: 15
            
            // 设备 ID（唯一标识）
            ColumnLayout {
                spacing: 5
                Layout.fillWidth: true
                
                Text {
                    text: "设备 ID *"
                    font.pixelSize: 14
                    color: "#666"
                }
                
                TextField {
                    id: deviceIdField
                    Layout.fillWidth: true
                    placeholderText: "例如：PLC_01（唯一标识，不可重复）"
                    font.pixelSize: 14
                    
                    background: Rectangle {
                        color: parent.activeFocus ? "#eff6ff" : "#f9fafb"
                        border.color: parent.activeFocus ? "#3b82f6" : "#e5e7eb"
                        border.width: 2
                        radius: 6
                    }
                }
            }
            
            // 设备名称
            ColumnLayout {
                spacing: 5
                Layout.fillWidth: true
                
                Text {
                    text: "设备名称 *"
                    font.pixelSize: 14
                    color: "#666"
                }
                
                TextField {
                    id: deviceNameField
                    Layout.fillWidth: true
                    placeholderText: "例如：1号生产线PLC"
                    font.pixelSize: 14
                    
                    background: Rectangle {
                        color: parent.activeFocus ? "#eff6ff" : "#f9fafb"
                        border.color: parent.activeFocus ? "#3b82f6" : "#e5e7eb"
                        border.width: 2
                        radius: 6
                    }
                }
            }
            
            // IP 地址
            ColumnLayout {
                spacing: 5
                Layout.fillWidth: true
                
                Text {
                    text: "IP 地址 *"
                    font.pixelSize: 14
                    color: "#666"
                }
                
                TextField {
                    id: ipAddressField
                    Layout.fillWidth: true
                    placeholderText: "例如：192.168.1.100"
                    font.pixelSize: 14
                    
                    background: Rectangle {
                        color: parent.activeFocus ? "#eff6ff" : "#f9fafb"
                        border.color: parent.activeFocus ? "#3b82f6" : "#e5e7eb"
                        border.width: 2
                        radius: 6
                    }
                }
            }
            
            // 端口和从站 ID（横向排列）
            RowLayout {
                spacing: 15
                Layout.fillWidth: true
                
                // 端口
                ColumnLayout {
                    spacing: 5
                    Layout.fillWidth: true
                    
                    Text {
                        text: "端口"
                        font.pixelSize: 14
                        color: "#666"
                    }
                    
                    SpinBox {
                        id: portField
                        Layout.fillWidth: true
                        from: 1
                        to: 65535
                        value: 502
                        editable: true
                        
                        background: Rectangle {
                            color: parent.activeFocus ? "#eff6ff" : "#f9fafb"
                            border.color: parent.activeFocus ? "#3b82f6" : "#e5e7eb"
                            border.width: 2
                            radius: 6
                        }
                    }
                }
                
                // 从站 ID
                ColumnLayout {
                    spacing: 5
                    Layout.fillWidth: true
                    
                    Text {
                        text: "从站 ID"
                        font.pixelSize: 14
                        color: "#666"
                    }
                    
                    SpinBox {
                        id: slaveIdField
                        Layout.fillWidth: true
                        from: 1
                        to: 247
                        value: 1
                        editable: true
                        
                        background: Rectangle {
                            color: parent.activeFocus ? "#eff6ff" : "#f9fafb"
                            border.color: parent.activeFocus ? "#3b82f6" : "#e5e7eb"
                            border.width: 2
                            radius: 6
                        }
                    }
                }
            }
            
            // 描述（可选）
            ColumnLayout {
                spacing: 5
                Layout.fillWidth: true
                
                Text {
                    text: "描述（可选）"
                    font.pixelSize: 14
                    color: "#666"
                }
                
                TextField {
                    id: descriptionField
                    Layout.fillWidth: true
                    placeholderText: "设备的详细描述信息"
                    font.pixelSize: 14
                    
                    background: Rectangle {
                        color: parent.activeFocus ? "#eff6ff" : "#f9fafb"
                        border.color: parent.activeFocus ? "#3b82f6" : "#e5e7eb"
                        border.width: 2
                        radius: 6
                    }
                }
            }
            
            // 提示信息
            Rectangle {
                Layout.fillWidth: true
                height: 1
                color: "#e5e7eb"
            }
            
            Text {
                text: "💡 提示：带 * 的字段为必填项"
                font.pixelSize: 12
                color: "#999"
                Layout.fillWidth: true
            }
        }
    }
    
    // ========================================
    // 底部按钮
    // ========================================
    footer: DialogButtonBox {
        background: Rectangle {
            color: "#f9fafb"
            Rectangle {
                width: parent.width
                height: 1
                color: "#e5e7eb"
                anchors.top: parent.top
            }
        }
        
        Button {
            text: "取消"
            DialogButtonBox.buttonRole: DialogButtonBox.RejectRole
            
            background: Rectangle {
                color: parent.hovered ? "#f3f4f6" : "white"
                border.color: "#d1d5db"
                border.width: 1
                radius: 6
                
                Behavior on color {
                    ColorAnimation { duration: 150 }
                }
            }
            
            contentItem: Text {
                text: parent.text
                font.pixelSize: 14
                color: "#666"
                horizontalAlignment: Text.AlignHCenter
                verticalAlignment: Text.AlignVCenter
            }
        }
        
        Button {
            text: "添加设备"
            DialogButtonBox.buttonRole: DialogButtonBox.AcceptRole
            
            background: Rectangle {
                color: parent.hovered ? "#2563eb" : "#3b82f6"
                radius: 6
                
                Behavior on color {
                    ColorAnimation { duration: 150 }
                }
            }
            
            contentItem: Text {
                text: parent.text
                font.pixelSize: 14
                font.bold: true
                color: "white"
                horizontalAlignment: Text.AlignHCenter
                verticalAlignment: Text.AlignVCenter
            }
        }
        
        onAccepted: {
            if (validateInput()) {
                root.deviceAdded(
                    deviceIdField.text.trim(),
                    deviceNameField.text.trim(),
                    ipAddressField.text.trim(),
                    portField.value,
                    slaveIdField.value,
                    descriptionField.text.trim()
                )
                root.accept()
                clearFields()
            }
        }
        
        onRejected: {
            root.reject()
            clearFields()
        }
    }
    
    // ========================================
    // JavaScript 函数
    // ========================================
    
    // 验证输入
    function validateInput() {
        if (deviceIdField.text.trim() === "") {
            showError("请输入设备 ID")
            deviceIdField.forceActiveFocus()
            return false
        }
        
        if (deviceNameField.text.trim() === "") {
            showError("请输入设备名称")
            deviceNameField.forceActiveFocus()
            return false
        }
        
        if (ipAddressField.text.trim() === "") {
            showError("请输入 IP 地址")
            ipAddressField.forceActiveFocus()
            return false
        }
        
        // 简单的 IP 地址格式验证
        var ipPattern = /^(\d{1,3}\.){3}\d{1,3}$/
        if (!ipPattern.test(ipAddressField.text.trim())) {
            showError("IP 地址格式不正确")
            ipAddressField.forceActiveFocus()
            return false
        }
        
        return true
    }
    
    // 清空字段
    function clearFields() {
        deviceIdField.text = ""
        deviceNameField.text = ""
        ipAddressField.text = ""
        portField.value = 502
        slaveIdField.value = 1
        descriptionField.text = ""
    }
    
    // 显示错误提示
    function showError(message) {
        console.warn("输入验证失败:", message)
        // 创建临时错误对话框
        var component = Qt.createComponent("ConfirmDialog.qml")
        if (component.status === Component.Ready) {
            var errorDialog = component.createObject(root.parent, {
                "parent": Overlay.overlay
            })
            errorDialog.showError("输入验证失败", message)
        }
    }
    
    // 打开对话框时聚焦第一个字段
    onOpened: {
        deviceIdField.forceActiveFocus()
    }
}

